﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using StaticPlugin;
using System.Windows.Forms;
using System.Security.Policy;

namespace MosWar
{
    class jMonyaSchatz : AJob
    {
        string status = "";
        jMonyaSchatzSetup setup = new jMonyaSchatzSetup();

        int minMoneyToPlay 
        {
            get 
            {

                return (int)setup.numMinMoneyToPlay.Value;
            }
        }
        int maxMoneyToStart
        {
            get
            {
                return (int)setup.numMaxMoneyToStart.Value;
            }
        }
        int gamePrice
        {
            get
            {
                if (setup.rb9Naperstkov.Checked) return 1500;
                return 500;
            }
        }
        int gameMode 
        {
            get 
            {
                if (setup.rb9Naperstkov.Checked) return 9;
                return 2;
            }
        }
        bool Critical = false;
        int DefaultPriority
        {
            get
            {
                return (int)setup.numPriority.Value;
            }
        }
        int CriticalPriority = 1;

        protected override bool getAvailable()
        {
            return (bool)Properties.Settings.Default["pCbAAvailable"];
        }


        #region Interface to AJob

        public override DialogResult showSetupDialog()
        {
            return setup.ShowDialog();
        }

        protected override string getName()
        {
            return "Игра с Шацом";
        }

        protected override string getStatus()
        {
            return status;
        }

        protected override int getPriority()
        {
            if (Critical) return CriticalPriority;
            return DefaultPriority;
        }

        #endregion

        #region Interface to Executer

        public override bool testRequirements(WebBrowser b)
        {
            Critical = false;
            if (b.Document == null)
            {
                return false;
            }
            if (b.Document.Body == null)
            {
                return false;
            }
            if (b.IsBusy)
            {
                return false;
            }

            if (b.Url.AbsolutePath.StartsWith("/thimble/")) // уже играем
            {
                Critical = true;
                return true;
            }
            int money = SkillsDetector.getMoney(b);
            if (money >= maxMoneyToStart) return true;
            else 
            {
                status = "Недостаточно денег. надо мин. " + maxMoneyToStart.ToString();
            }
            if (money < 0) 
            {
                status = "Ошибка определения денег!";
            }
            return false;
        }

        public override void initActions()
        {
            actions.Clear();
            actions.Add(new Action("GoToMetro", GoToMetro));
            actions.Add(new Action("GoToMonya", GoToMonya));
            actions.Add(new Action("AnalyzeStatus", AnalyzeStatus));
        } 

        #endregion

        #region Stuff functions

        void ChoiceGame(WebBrowser b, int num)
        {
            status = "Начинаем играть. Наперстков будет " + num.ToString();
            b.Navigate(b.Url.Scheme + "://" + b.Url.Host + "/thimble/play/" + num.ToString() + "/");
            actions.Add(new Action("проанализировать после запуска игры", AnalyzeStatus));
            Console.WriteLine("actions appended with AnalyzeStatus()");
        }

        #endregion

        #region Actions

        void getGameButtons(WebBrowser b, out HtmlElement choice2, out HtmlElement choice9) 
        {
            choice9 = null;
            choice2 = null;
            HtmlElement thimbleControls = b.Document.Body.GetElementsByTagName("div")["thimble-controls"];
            if (thimbleControls == null) return;
            if (thimbleControls.Style.IndexOf("DISPLAY: none;")>-1) return;
            foreach (HtmlElement elem in b.Document.Body.GetElementsByTagName("div"))
            {
                if (elem.GetAttribute("className") != "button thimble-play") continue;
                if (elem.GetAttribute("data-count").ToString() == "2" && !elem.ClientRectangle.IsEmpty) choice2 = elem;
                if (elem.GetAttribute("data-count").ToString() == "9" && !elem.ClientRectangle.IsEmpty) choice9 = elem;
            }
        }

        void GoToMetro(WebBrowser b)
        {
            status = "Идем в метро";
            if (b.Url.AbsolutePath != "/metro/" && !b.Url.AbsolutePath.StartsWith("/thimble"))
            {
                b.Navigate(b.Url.Scheme + "://" + b.Url.Host + "/metro/");
            }
        }

        void GoToMonya(WebBrowser b)
        {
            status = "Идем к Моне";
            if (!b.Url.AbsolutePath.StartsWith("/thimble"))
                b.Navigate(b.Url.Scheme + "://" + b.Url.Host + "/thimble/start/");
        }

        void LeaveGame(WebBrowser b)
        {
            status = "Отходим от наперстков";
            b.Navigate(b.Url.Scheme + "://" + b.Url.Host + "/thimble/leave/");
        }

        void ActivateThimbleRandom(WebBrowser b)
        {
            Random r = new Random();
            HtmlElement thimbles = WebParserEx.getTagByClassName(b.Document.Body, "p", "thimbles");
            if (thimbles == null)
            {
                actions.Clear();
                status = "Не смогли найти наперстки!";
                Console.WriteLine("ActivateThimbleRandom:: thimbles==null");
                return;
            }
            //int count = 0;
            List<HtmlElement> thimbleList = new List<HtmlElement>();
            foreach (HtmlElement thimble in thimbles.GetElementsByTagName("i")) 
            {
                if (thimble.GetAttribute("className") == "icon thimble-closed-active") //Закрытый наперсток
                {
                    thimbleList.Add(thimble);
                }
            }
            int thimbleNum = r.Next(0, thimbleList.Count);
            string thimbleIndex = thimbleList[thimbleNum].GetAttribute("id").Replace("thimble", "");
            thimbleList[thimbleNum].InvokeMember("click");
            Console.WriteLine("Нашли " + thimbleList.Count.ToString() + " наперстка(ов). Выбираем №" + thimbleIndex);
            //b.Navigate(b.Url.Scheme + "://" + b.Url.Host + "/thimble/guess/" + thimbleIndex + "/");
            actions.Add(new Action("", AnalyzeStatus));
            Console.WriteLine("actions appended with AnalyzeStatus()");
        }

        void ChoiceGame(WebBrowser b)
        {
            HtmlElement choice2 = null, choice9 = null;
            getGameButtons(b, out choice2, out choice9);
            if (SkillsDetector.getMoney(b) > minMoneyToPlay + 1500 && choice9 != null)
            {
                status = "Играем в 9 наперстков";
                choice9.InvokeMember("click");
                actions.Add(new Action("ChoiceGame->AnalyzeStatus", AnalyzeStatus));
                return;
            }
            if (SkillsDetector.getMoney(b) > minMoneyToPlay + 500 && choice2 != null)
            {
                status = "Играем в 2 наперсткa";
                choice2.InvokeMember("click");
                actions.Add(new Action("ChoiceGame->AnalyzeStatus", AnalyzeStatus));
                return;
            }
            LeaveGame(b);
            return;
        }

        void AnalyzeStatus(WebBrowser b)
        {
            int money = SkillsDetector.getMoney(b);
            status = "Анализ состояния игры с Моней";
            if (money < 0)
            {
                Console.WriteLine("AnalyzeStatus:: Ошибка анализа кол-ва денег");
                return;
            }
            HtmlElement thimbleChoice = WebParserEx.getTagByClassName(b.Document.Body, "div", "thimble-choose");
            if (thimbleChoice == null) // Не играем в наперстки
            {
                Console.WriteLine("AnalyzeStatus::thimbleChoice = null");
                return;
            }

            HtmlElement choice2 = null, choice9 = null;
            getGameButtons(b, out choice2, out choice9);
            if (choice2 != null || choice9 != null)
            {
                status = "Выбор подходящей игры";
                actions.Add(new Action("ChoiceGame", ChoiceGame));
                return;
            }

            // Не нашли ни одной ссылки на начало игры
            HtmlElement openThimble = WebParserEx.getTagByClassName(thimbleChoice, "i", "icon thimble-closed-active");
            if (openThimble != null) //Есть хотя бы 1 закрытый наперсток
            {
                status = "Играем в наперсток";
                actions.Add(new Action("ActivateThimbleRandom", ActivateThimbleRandom));
                Console.WriteLine("actions appended with ActivateThimbleRandom()");
                return;
            }
            Console.WriteLine("Нет ни открытых наперстков ни выбора игры");
            //throw new Exception("Нет ни открытых наперстков ни выбора игры");
        } 
        #endregion
    }
}
